package com.sxj.PDMS.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxj.PDMS.model.entity.ActivistApplicationInformationList;
import com.sxj.PDMS.model.entity.Notice;
import com.sxj.PDMS.model.vo.NoticeResponse;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.service.NoticeService;
import com.sxj.PDMS.mapper.NoticeMapper;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {

    private final NoticeMapper noticeMapper;

    @Autowired
    public NoticeServiceImpl(NoticeMapper noticeMapper) {
        this.noticeMapper = noticeMapper;
    }

    @Override
    public PagingQueryResponse<NoticeResponse> getAllNotices(Integer page, Integer pageSize) {
        Integer start = (page - 1) * pageSize;
        List<Notice> noticeLists = noticeMapper.selectAll(start, pageSize);
        Long total = noticeMapper.selectTotal();
        PagingQueryResponse<NoticeResponse> pagingQueryResponse = new PagingQueryResponse<>();

        List<NoticeResponse> noticeResponses = new ArrayList<>();

        for (Notice notice : noticeLists) {
            // 构建 NoticeResponse 对象，包含标题、简介和第一张图片的位置
            NoticeResponse noticeResponse = new NoticeResponse();
            noticeResponse.setId(notice.getId());
            noticeResponse.setTitle(notice.getTitle());
            noticeResponse.setSummary(notice.getIntro());
            noticeResponse.setCreateTime(notice.getCreateTime());

            // 获取通知内容中的第一张图片位置
            String firstImageUrl = extractFirstImageUrlFromFile(notice.getContent());
            noticeResponse.setFirstImageUrl(firstImageUrl);

            noticeResponses.add(noticeResponse);

        }
        pagingQueryResponse.setRows(noticeResponses);

        pagingQueryResponse.setTotal(total);

        return pagingQueryResponse;
    }

    @Override
    public List<Notice> get6Notices() {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        queryWrapper.last("limit 3"); // MySQL中使用limit关键字获取前6条记录

        return noticeMapper.selectList(queryWrapper);
    }

    @Override
    public List<Notice> get46Notices() {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        queryWrapper.last("LIMIT 3 OFFSET 3"); // MySQL中使用limit关键字获取前6条记录

        return noticeMapper.selectList(queryWrapper);
    }

    @Override
    public Boolean deleteById(Long id) {
        Notice notice = noticeMapper.selectById(id);
        int rowsAffected = noticeMapper.deleteById(id);
        if (rowsAffected > 0) {
            // 删除成功 删除对应内容所存在的文件
            if (!StringUtils.isEmpty(notice.getContent())) {
                deleteFileIfExists(notice.getContent());
            }
            return true;
        }

        return false;
    }

    private void deleteFileIfExists(String filePath) {
        try {
            Path path = Paths.get(filePath);
            if (Files.exists(path)) {
                Files.delete(path);
            }
        } catch (IOException e) {
            log.error("删除文件失败: {}");
        }
    }


    private String extractFirstImageUrlFromFile(String filePath) {
        try {
            // 读取文件内容为字符串
            String htmlContent = readFileToString(filePath);

            // 使用 Jsoup 解析 HTML 内容，获取第一张图片的地址
            return extractFirstImageUrl(htmlContent);
        } catch (IOException e) {
            log.error("读取文件内容失败: {}");
            return null;
        }
    }

    /**
     * 将文件内容读取为字符串
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    private String readFileToString(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        byte[] bytes = Files.readAllBytes(path);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    private String extractFirstImageUrl(String htmlContent) {
        Document doc = Jsoup.parse(htmlContent);
        Elements imgElements = doc.select("img");

        if (imgElements != null && !imgElements.isEmpty()) {
            Element firstImg = imgElements.first();
            String imageUrl = firstImg.attr("src");
            return imageUrl;
        }

        return null; // 如果没有找到图片则返回 null
    }


}





